package com.csp.base;

import com.csp.domain.TUsers;
import com.csp.utils.AAContants;
import com.csp.utils.AAUtils;
import com.csp.utils.DataTablePageUtil;
import com.csp.utils.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liupengchao on 2017/3/29.
 * @author liupengchao
 * @version 1.0
 */
public class BaseController<T> {

    public final static Logger logger = LoggerFactory.getLogger(BaseController.class);


    /**
     * 获取当前登陆用户信息
     * @return
     */
    public TUsers getCurrentTUser(HttpSession session){

        TUsers tUsers=null;
        if(session.getAttribute(AAContants.globalbase.SESSION_LOGIN_USER)!=null){

        }
        return  tUsers;
    }

    /**
     * writeJson
     * @param flag
     * @param msg
     */
    public void writeJson(PrintWriter out, String flag, String msg) {

        Map outDto = new HashMap();
        outDto.put("success",flag);
        outDto.put("msg",msg);
        JSONObject js= JSONUtils.toJSONObject(outDto);
        write(out,js.toString());
    }


    /**
     * 输出
     * @param str
     */
    public void write(PrintWriter out,String str) {

        out.write(str);
        out.flush();
        out.close();
    }


    /**
     * 输出writeJsonEmpty
     */
    public void writeJsonEmpty(PrintWriter out)
    {
        Map map=new HashMap();
        map.put("success","0");
        map.put("data","");
        JSONObject js= JSONUtils.toJSONObject(map);
        out.write(js.toString());
        out.flush();
        out.close();
    }

    /**
     * 获取datatable的实例和生成分页开始结束位置
     * @param request
     * @return
     */
    public DataTablePageUtil<T> getTableAndPage(HttpServletRequest request,T cls){
        DataTablePageUtil<T> dataTable = new DataTablePageUtil<T>(request);
        PageHelper.startPage(dataTable.getPage_num(),dataTable.getLength());//必须放在分页查询之前不然分页效果无法实现
        return dataTable;
    }

    /**
     * datatable列表
     * @param request
     * @param list
     * @param cls
     * @param out
     */
    public void callbackJson(HttpServletRequest request,List list, T cls ,PrintWriter out, String msg,DataTablePageUtil<T> dataTable){
        try {
            if(!AAUtils.isEmpty(list)) {
                PageInfo<T> pageInfo = new PageInfo<T>(list);
                dataTable.setDraw(dataTable.getDraw());
                dataTable.setData(pageInfo.getList());
                dataTable.setRecordsTotal((int) pageInfo.getTotal());
                dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
                String jsonString = JSONUtils.toJSONString2(dataTable);
                out.write(jsonString);
            }else {
                dataTable.setDraw(dataTable.getDraw());
                dataTable.setData(new ArrayList<>());
                dataTable.setRecordsTotal(0);
                dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
                String jsonString = JSONUtils.toJSONString2(dataTable);
                //System.out.println("[jsonString-empty]:"+jsonString);
                out.write(jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(msg +"异常:{}",e.getMessage());
            dataTable.setDraw(dataTable.getDraw());
            dataTable.setData(new ArrayList<>());
            dataTable.setRecordsTotal(0);
            dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
            String jsonString = JSONUtils.toJSONString2(dataTable);
            System.out.println("[jsonString-error]:"+jsonString);
            out.write(jsonString);
        }
    }

    /**
     * 新增返回前端信息公共方法
     * @param out
     * @param flag
     * @param msg
     */
    public void operateCommon(PrintWriter out,int flag,String msg){
        try {
            if(flag>0){
                writeJson(out, AAContants.globalbase.Z_TRUE,AAContants.tipmsg.SUCCESS);
            }else {
                writeJson(out, AAContants.globalbase.Z_FALSE,msg+"失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(msg+"异常：{}",e.getMessage());
            writeJson(out, AAContants.globalbase.Z_FALSE,AAContants.tipmsg.DB_ERROR);
        }
    }
}
